from datetime import timedelta

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.core.config import settings
from app.core.database import get_db
from app.schemas.auth import Token, LoginRequest, ChangePasswordRequest, UserAuthInfo
from app.schemas.user import User as UserSchema, UserCreate
from app.services.auth_service import AuthService
from app.services.user_service import UserService
from app.api.deps import get_current_active_user
from app.api.dependencies import get_auth_service, get_user_service, get_auth_and_user_services
from app.models.user import User
from app.core.logging import get_logger

logger = get_logger(__name__)
# 移除tags参数，让在api.py中统一设置
router = APIRouter(prefix="/auth")


def _safe_int(value):
    """安全地将值转换为int类型"""
    if hasattr(value, 'value'):  # SQLAlchemy列对象
        return int(value.value) if value.value is not None else 0
    elif hasattr(value, '__int__'):  # 可以转换为int的对象
        return int(value)
    else:  # 普通值
        return int(value) if value is not None else 0


@router.post("/login", response_model=Token)
async def login(
    login_data: LoginRequest,
    auth_service: AuthService = Depends(get_auth_service)
):
    """用户登录"""
    logger.info(f"Login attempt for email: {login_data.email}")
    
    try:
        logger.info("Attempting to authenticate user...")
        user = auth_service.authenticate_user(login_data.email, login_data.password)
        logger.info(f"Authentication result: {user is not None}")
        
        if not user:
            logger.warning(f"Authentication failed for email: {login_data.email}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
        
        logger.info(f"Authentication successful for user_id: {user.id}")
        
        logger.info("Creating access token...")
        access_token = auth_service.create_access_token(
            data={"user_id": _safe_int(user.id)},  # 安全转换为int类型
            expires_delta=timedelta(minutes=getattr(settings, 'ACCESS_TOKEN_EXPIRE_MINUTES', 30))
        )
        logger.info("Access token created successfully")
        
        logger.info("Creating refresh token...")
        refresh_token = auth_service.create_refresh_token(_safe_int(user.id))  # 安全转换为int类型
        logger.info("Refresh token created successfully")
        
        logger.info("Creating response token...")
        token_response = Token(
            access_token=access_token,
            refresh_token=refresh_token,
            token_type="bearer",
            expires_in=getattr(settings, 'ACCESS_TOKEN_EXPIRE_MINUTES', 30) * 60
        )
        logger.info("Token response created successfully")
        
        return token_response
        
    except HTTPException:
        # 重新抛出HTTP异常
        logger.warning("Re-raising HTTP exception")
        raise
    except Exception as e:
        logger.error(f"Login error: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录处理失败"
        )


@router.post("/register", response_model=UserSchema)
async def register(
    user_data: UserCreate,
    user_service: UserService = Depends(get_user_service)
):
    """用户注册"""
    try:
        user = user_service.create_user(user_data)
        return user
    except HTTPException as e:
        raise e
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="用户创建失败"
        )


@router.post("/refresh", response_model=Token)
async def refresh_token(
    refresh_token: str,
    auth_service: AuthService = Depends(get_auth_service)
):
    """刷新访问令牌"""
    new_access_token = auth_service.refresh_access_token(refresh_token)
    
    if not new_access_token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的刷新令牌"
        )
    
    return Token(
        access_token=new_access_token,
        token_type="bearer",
        expires_in=getattr(settings, 'ACCESS_TOKEN_EXPIRE_MINUTES', 30) * 60
    )


@router.get("/me", response_model=UserAuthInfo)
async def get_current_user_info(
    current_user: User = Depends(get_current_active_user),
    auth_service: AuthService = Depends(get_auth_service)
):
    """获取当前用户信息"""
    try:
        logger.debug("获取用户信息", extra={"user_id": _safe_int(current_user.id)})  # 安全转换为int类型
        
        user_info = auth_service.get_current_user_info(_safe_int(current_user.id))  # 安全转换为int类型
        
        logger.info("用户信息获取成功")
        return user_info
        
    except Exception as e:
        logger.error(
            "获取用户信息失败",
            extra={"error": str(e), "error_type": type(e).__name__},
            exc_info=True
        )
        
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户信息失败，请稍后重试"
        )


@router.post("/change-password")
async def change_password(
    password_data: ChangePasswordRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """修改密码"""
    auth_service = AuthService(db)
    success = auth_service.change_password(
        _safe_int(current_user.id),  # 安全转换为int类型
        password_data.current_password,
        password_data.new_password
    )
    
    if not success:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="密码修改失败，请检查当前密码是否正确"
        )
    
    return {"message": "密码修改成功"}


@router.post("/logout")
async def logout(
    current_user: User = Depends(get_current_active_user)
):
    """用户登出"""
    # 在实际应用中，这里可以处理令牌撤销
    return {"message": "登出成功"}